""" 
    Aplicación OKRUTV
"""

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication #pylint: disable=no-name-in-module
import OKRUTV_main
import os
import pathlib
import subprocess as sp
import logging
from app import Resolucion, Canal, ChannelDict
import requests


########################## Logging ################################################
def loggingStart():
        logging.basicConfig(filename='OKRUTV.log', filemode="w")

########################## PyQT class #############################################

class OkryTvClass(QtWidgets.QMainWindow, OKRUTV_main.Ui_MainWindow):
    def __init__(self, parent=None):
        super(OkryTvClass, self).__init__(parent)
        self.setupUi(self)
        # Variables de aplicación
        self.genre = ""
        self.serie = ""
        self.channelGenre = ""
        self.chapter = ""
        self.resolutions = []
        self.links = []
        self.chapters = []
        self.channels = []
        self.resolution = 3
        self.content = "Series"
        # Cargar Generos
        self.load_genres()
        # Deshabilitar propiedades
        self.Formato.setEnabled(False)
        self.verContinuo.setEnabled(False)
        self.labelFormato.setEnabled(False)
        # Métodos de conexión
        self.lista_generos.itemActivated.connect(self.genre_choosed)
        self.lista_series.itemActivated.connect(self.serie_choosed)
        self.Formato.currentIndexChanged.connect(self.FormatChange)
        self.lista_capitulos.itemActivated.connect(self.chapter_choosed)

    ######################### Auxiliares ###########################################

    def get_subdirs(self, dir):
        # Función que regresa todos los subdirectorios de un directorio:
        # Args:     dir: Ruta de un directorio
        # Return:   []: Lista con los subdirectorios
        return [name for name in os.listdir(dir)
            if os.path.isdir(os.path.join(dir, name))]     

    def get_files(self, dir):
        # Función que regresa todos los archivos no subdirectorios de un directorio:
        # Args:     dir: Ruta de un directorio
        # Return:   []: Lista con los subdirectorios
        return [name for name in os.listdir(dir)
            if not os.path.isdir(os.path.join(dir, name))]

    def load_genres(self):
        genres = self.get_subdirs(str(pathlib.Path())+'/app/Listas')
        i = genres.index('Desconocidas')
        genres.pop(i)
        self.lista_generos.addItems(genres)
        self.lista_generos.sortItems()
    
    def loadChannelsTypeList(self):
        self.lista_series.clear()
        self.content = "Channels"
        channelsTypes = self.get_subdirs(str(pathlib.Path())+'/app/Listas/Canales de TV')
        self.lista_series.addItems(channelsTypes)
        self.lista_series.sortItems()

    def loadSeries(self, genre):
        self.lista_series.clear()
        self.content = "Series"
        series = self.get_files(str(pathlib.Path())+'/app/Listas/'+genre)
        # Bloque que elimina los .csv de "series"
        porEliminar = []
        for i in range(0,len(series)):
            if '.m3u' not in series[i]:
                  porEliminar.append(series[i])
        for e in porEliminar:
            series.remove(e)
        ##########################################
        
        self.lista_series.addItems(series)
        self.lista_series.sortItems()

    def loadResolutions(self):
        self.resolutions = []
        f = open(f"app/Listas/{self.genre}/{self.serie}.csv",'r')

        for line in f.readlines():
            lista = line.split(';')
            lista.pop(0)
            self.resolutions.append(lista)


    def loadLinks(self):
        self.links = []
        f = open(f"app/Listas/{self.genre}/{self.serie}.m3u",'r')
        for line in f.readlines():
            if 'https://' in line:
                self.links.append(line.strip('\n'))
            elif '#EXTM3U' in line:
                pass
            else:
                self.chapters.append(line.split(',',maxsplit=1)[1].strip('\n'))
    


    ####################### Métodos de eventos ####################################

    def genre_choosed(self,item):
        self.genre = item.text()
        if item.text() == 'Canales de TV':
            self.loadChannelsTypeList()
        else:
            self.loadSeries(item.text())

    def serie_choosed(self,item):
        self.Formato.clear()
        self.Formato.addItems(['movil','lowest','low','sd','hd'])
        self.Formato.setEnabled(True)
        self.Formato.setCurrentIndex(3)
        self.labelFormato.setEnabled(True)
        self.lista_capitulos.clear()
        self.chapters.clear()
        if self.content == "Series":    
            self.verContinuo.setChecked(False)
            self.verContinuo.setEnabled(True)
            self.serie = item.text().split('.')[0]
            self.Propiedades.setTitle(self.serie)           
            self.loadLinks()
            self.loadResolutions()
            self.lista_capitulos.addItems(self.chapters)
        elif self.content == "Channels":
            self.channelGenre = item.text()
            self.Propiedades.setTitle(self.channelGenre)
            self.channels = self.get_files(str(pathlib.Path())+'/app/Listas/Canales de TV/'+item.text())
            self.lista_capitulos.addItems(self.channels)
            self.lista_capitulos.sortItems()
        


    def FormatChange(self,i):
        self.resolution = i
     
    def chapter_choosed(self, item):
        if self.content == "Series":
            self.chapter = self.chapters.index(item.text())
            if self.resolution < len(self.resolutions[self.chapter]):
                res = self.resolution
            else:
                res = len(self.resolutions[self.chapter])-1
            if self.verContinuo.isChecked():
                for i in range(self.chapter,len(self.chapters)):
                    if self.resolution > len(self.resolutions[self.chapter]):
                        res = self.resolution
                    else:
                        res = len(self.resolutions[self.chapter])-1
                    sp.call(['mpv/mpv.com', self.links[i], f"--ytdl-format={self.resolutions[i][res]}", '--fs'])
            else:
                logging.warning(f"""Resoluciones":
                    {self.resolutions}
                    Capitulo: {self.chapter}
                    Tipo de Resolución: {res}
                    Link del capítulo: {self.links[self.chapter]}
                    Resolución: {self.resolutions[self.chapter][res]}
                    Comando: mpv {self.links[self.chapter]} --ytdl-format={self.resolutions[self.chapter][res]} --fs
                """)
                sp.call(['mpv/mpv.com', self.links[self.chapter], f"--ytdl-format={self.resolutions[self.chapter][res]}", '--fs'])
        elif self.content == "Channels":
            line = ChannelDict.ch_d[" "+item.text()]
            #print(line)
            f = open('app/Listas/Canales de TV/mx.m3u')
            i = 0
            for l in f.readlines():
                if i == line:
                    link = l
                i +=1
            #print(link)
            f.close()
            myfile = requests.get(link)
            open('app/Listas/Canales de TV/'+self.channelGenre+'/'+item.text(), 'wb').write(myfile.content)           
            f = open('app/Listas/Canales de TV/'+self.channelGenre+'/'+item.text(),'r')
            i = 0
            for line in f.readlines():
                link = line
                i+=1
                if i == self.resolution*3:
                    break
            sp.call(['mpv/mpv.com',link,'--fs'])

if __name__ == '__main__':
    loggingStart()
    app = QApplication(sys.argv)
    main = OkryTvClass()
    main.show()
    app.exec_()